package com.ruoyi.web.controller.shop.goods.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OSSUtil;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.web.controller.shop.goods.domain.ShopGoods;
import com.ruoyi.web.controller.shop.goods.service.IShopGoodsService;
import com.ruoyi.web.controller.shop.imgs.domain.ShopImages;
import com.ruoyi.web.controller.shop.imgs.service.IShopImagesService;
import com.ruoyi.web.controller.shop.shop.domain.ShopShop;
import com.ruoyi.web.controller.shop.shop.service.IShopShopService;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import static com.ruoyi.web.utils.initVodClient.getPlayInfo;
import static com.ruoyi.web.utils.initVodClient.initVodClient;


/**
 * 店铺商品Controller
 * 
 * @author ruoyi
 * @date 2020-10-17
 */
@RestController
@RequestMapping("/goods")
public class ShopGoodsController extends BaseController
{
    @Autowired
    private IShopGoodsService shopGoodsService;

    @Autowired
	private TokenService tokenService;

    @Autowired
	private IShopShopService shopShopService;

    @Autowired
	private IShopImagesService shopImagesService;

    /**
     * 查询店铺商品列表
     */
//    @PreAuthorize("@ss.hasPermi('shop:goods:list')")
    @GetMapping("/list")
    public AjaxResult list(ShopGoods shopGoods)
    {
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		SysUser user = loginUser.getUser();
		//查询店铺信息
		ShopShop shopShop = this.shopShopService.selectShopShopById(user.getShopId());
		if(shopShop==null){
			return AjaxResult.error("门店不存在");
		}
		shopGoods.setShopId(shopShop.getId());
		shopGoods.setDelFlag(0);
        startPage();
        List<ShopGoods> list = shopGoodsService.selectShopGoodsList(shopGoods);
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 导出店铺商品列表
     */
//    @PreAuthorize("@ss.hasPermi('shop:goods:export')")
//    @Log(title = "店铺商品", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, ShopGoods shopGoods) throws IOException
//    {
//        List<ShopGoods> list = shopGoodsService.selectShopGoodsList(shopGoods);
//        ExcelUtil<ShopGoods> util = new ExcelUtil<ShopGoods>(ShopGoods.class);
//        util.exportExcel(response, list, "goods");
//    }

    /**
     * 获取店铺商品详细信息
     */
//    @PreAuthorize("@ss.hasPermi('shop:goods:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
		ShopGoods shopGoods = shopGoodsService.selectShopGoodsById(id);
		if(shopGoods!=null){
			ShopImages shopImages = new ShopImages();
			shopImages.setLinkId(id);
			shopImages.setAddress(3);
			shopGoods.setBannerList(this.shopImagesService.selectShopImagesList(shopImages));
			shopImages.setAddress(4);
			shopGoods.setInfoImgList(this.shopImagesService.selectShopImagesList(shopImages));

			shopImages.setAddress(6);
			List<ShopImages> videos = this.shopImagesService.selectShopImagesList(shopImages);
			if(videos.size()>0){
				try {
					//            map.put("video",banner);
					ShopImages si = videos.get(0);
					String video =si.getImgurl();
					DefaultAcsClient client = initVodClient();
					GetPlayInfoResponse response = new GetPlayInfoResponse();
					response = getPlayInfo(client,video);
					List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
					//播放地址
					for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
						System.out.print("PlayInfo.PlayURL = " + playInfo.getPlayURL() + "\n");
						si.setImgurl(playInfo.getPlayURL());
						shopGoods.setVideoTop(si);
					}
				}catch (Exception e){
					shopGoods.setVideoTop(videos.get(0));
				}

			}else {
				shopGoods.setVideoTop(null);
			}
			shopImages.setAddress(7);
			List<ShopImages> videosB = this.shopImagesService.selectShopImagesList(shopImages);
			if(videosB.size()>0){
				try {
					//            map.put("video",banner);
					ShopImages si = videosB.get(0);
					String video =si.getImgurl();
					DefaultAcsClient client = initVodClient();
					GetPlayInfoResponse response = new GetPlayInfoResponse();
					response = getPlayInfo(client,video);
					List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
					//播放地址
					for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
						System.out.print("PlayInfo.PlayURL = " + playInfo.getPlayURL() + "\n");
//					shopGoods.setVideoBottom(playInfo.getPlayURL());
						si.setImgurl(playInfo.getPlayURL());
						shopGoods.setVideoBottom(si);
					}
				}catch (Exception e){
					shopGoods.setVideoBottom(videosB.get(0));
				}

			}else {
				shopGoods.setVideoBottom(null);
			}
		}
		return AjaxResult.success(shopGoods);
    }

    /**
     * 新增店铺商品
     */
//    @PreAuthorize("@ss.hasPermi('shop:goods:add')")
    @Log(title = "店铺商品", businessType = BusinessType.INSERT)
    @PostMapping
	@Transactional
    public AjaxResult add(@RequestBody ShopGoods shopGoods)
    {
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		SysUser user = loginUser.getUser();
		//查询店铺信息
		ShopShop shopShop = this.shopShopService.selectShopShopById(user.getShopId());
		if(shopShop==null){
			return AjaxResult.error("门店不存在");
		}
		//判断现在的商品数量是否到达店铺上线
		Integer goodsNum = this.shopGoodsService.findSumGoods(shopShop.getId());
		if(goodsNum>=shopShop.getMaxGoods()){
			return AjaxResult.error("商品数量达到最大值 不可添加");
		}
    	//补充商品数据
		shopGoods.setCheck(0);
		shopGoods.setShopId(shopShop.getId());
		shopGoods.setNumView(0L);
		shopGoods.setCreateId(user.getUserId());
		shopGoods.setCreateAt(DateUtils.getNowDate());
		shopGoods.setDisabled(1);
		shopGoods.setDelFlag(0);
		//添加商品信息
		shopGoodsService.insertShopGoods(shopGoods);
		//添加图片信息
		if(shopGoods.getBannerList()!=null){
			for(ShopImages shopImages:shopGoods.getBannerList()){
				shopImages.setLinkId(shopGoods.getId());
				shopImages.setAddress(3);
				shopImages.setCreateAt(DateUtils.getNowDate());
				shopImages.setCreateId(user.getUserId());
				shopImages.setStatus(0);
				shopImages.setShopId(shopShop.getId());
				this.shopImagesService.insertShopImages(shopImages);
			}
		}
		//添加图片信息
		if(shopGoods.getInfoImgList()!=null){
			for(ShopImages shopImages:shopGoods.getInfoImgList()){
				shopImages.setLinkId(shopGoods.getId());
				shopImages.setAddress(4);
				shopImages.setCreateAt(DateUtils.getNowDate());
				shopImages.setCreateId(user.getUserId());
				shopImages.setStatus(0);
				shopImages.setShopId(shopShop.getId());
				this.shopImagesService.insertShopImages(shopImages);
			}
		}
        return AjaxResult.success();
    }

    /**
     * 修改店铺商品
     */
//    @PreAuthorize("@ss.hasPermi('shop:goods:edit')")
    @Log(title = "店铺商品", businessType = BusinessType.UPDATE)
    @PutMapping
	@Transactional
    public AjaxResult edit(@RequestBody ShopGoods shopGoods)
    {
    	//查询原本的商品信息
		ShopGoods oldGoods = this.shopGoodsService.selectShopGoodsById(shopGoods.getId());
		if(oldGoods==null){
			return AjaxResult.success("商品不存在");
		}
		//判断是否修改重要信息  修改的话  需要下架进行审核
		if(!StringUtils.isBlank(shopGoods.getName())&&!oldGoods.getName().equals(shopGoods.getName())){
			shopGoods.setCheck(0);
			shopGoods.setDisabled(1);
		}
		if(!StringUtils.isBlank(shopGoods.getTitle())&&!oldGoods.getTitle().equals(shopGoods.getTitle())){
			shopGoods.setCheck(0);
			shopGoods.setDisabled(1);
		}
		if(!StringUtils.isBlank(shopGoods.getImg())&&!oldGoods.getImg().equals(shopGoods.getImg())){
			shopGoods.setCheck(0);
			shopGoods.setDisabled(1);
		}
		if(!StringUtils.isBlank(shopGoods.getNote())&&!oldGoods.getNote().equals(shopGoods.getNote())){
			shopGoods.setCheck(0);
			shopGoods.setDisabled(1);
		}
		shopGoodsService.updateShopGoods(shopGoods);
        return AjaxResult.success();
    }

    /**
     * 删除店铺商品
     */
//    @PreAuthorize("@ss.hasPermi('shop:goods:remove')")
    @Log(title = "店铺商品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{id}")
	@Transactional
    public AjaxResult remove(@PathVariable String id)
    {
    	//删除商品信息
		shopGoodsService.deleteShopGoodsById(id);
		//删除商品图片信息
		shopImagesService.deleteByShopId(id);
        return AjaxResult.success();
    }



}
